package com.aispeech.astools.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import com.aispeech.astools.recorder.RecordListener;
import com.aispeech.astools.recorder.SerialRecord;

import androidx.annotation.Nullable;


/**
 * @author rain  07.10 2019
 */

public class SerialTestService extends Service {

    private final String TAG = "SerialTestService";

    private SerialCallBack mCallBack;
    private SerialRecord mSrd;
    private boolean isOpen = false;

    private MutualBinder mBinder = new MutualBinder();

    public class MutualBinder extends Binder {

        public boolean openPort(String port, int baudrate, SerialCallBack callBack) {
            Log.d(TAG, "openPort with: port = " + port + ", baudrate = " + baudrate + "");
            mCallBack = callBack;
            initSerialRecord();
            isOpen = mSrd.start(port, baudrate);
            return isOpen;
        }

        public void closePort() {
            Log.d(TAG, "closePort");
            if (null != mSrd) {
                mSrd.stop();
                mSrd.destroy();
            }
            isOpen = false;
        }

        public boolean isOpen() {
            return isOpen;
        }
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");
    }

    private void initSerialRecord() {
        mSrd = new SerialRecord();
        mSrd.init(getApplication(), new RecordListener() {
            @Override
            public void onBuffer(byte[] data) {
                mCallBack.onData(data);
            }

            @Override
            public void onEvent(EVENT event) {

            }

            @Override
            public void onError(String info) {
                mCallBack.onMessage(info);
            }
        });
    }


    public interface SerialCallBack {

        void onData(byte[] data);

        void onMessage(String event);
    }

}
